<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\blog\controller;

use cmf\controller\AdminBaseController;
use think\Db;

class UserController extends AdminBaseController
{

    /**
     * 管理员列表
     * @adminMenu(
     *     'name'   => '管理员',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $where = ["user_type" => 1];
        /**搜索条件**/
        $userLogin = $this->request->param('user_login');
        $userEmail = trim($this->request->param('user_email'));
        if ($userLogin) {
            $where['user_login'] = ['like', "%$userLogin%"];
        }
        /*if ($userEmail) {
            $where['user_email'] = ['like', "%$userEmail%"];;
        }*/
        //按级别显示roleid
        $adminid = cmf_get_current_admin_id();
        $adminUinfo=get_operator_data($adminid);
        $user_list=get_user_list($adminid);
        $uid_list_str='';
        if($user_list){
            $uid_list_str=toStr($user_list,'userid').','.$adminid;
        }
        $where['id']=array('in',$uid_list_str);
        $users = Db::name('user')->where($where)->order("id DESC")->paginate(10);
        //echo Db::name('user')->getlastsql();
        $users->appends(['user_login' => $userLogin, 'user_email' => $userEmail]);
        // 获取分页显示
        $page = $users->render();
        $rolesSrc = Db::name('role')->select();
        $roles    = [];
        foreach ($rolesSrc as $r) {
            $roleId           = $r['id'];
            $roles["$roleId"] = $r;
        }
        $this->assign("page", $page);
        $this->assign("roles", $roles);
        $this->assign("users", $users);
        $this->assign("role_type", $adminUinfo['role_type']);
        return $this->fetch();
    }

    /**
     * 管理员添加
     * @adminMenu(
     *     'name'   => '管理员添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加',
     *     'param'  => ''
     * )
     */
    /*
     * 2018-6-02查询上下级关系
     * */
    public function add()
    {
        $adminid = cmf_get_current_admin_id();
        $uinfo=get_operator_data($adminid);//会员的个人信息
        //var_dump($uinfo);die();
        $con['status']=1;
        $con['id']=array('gt',$uinfo['role_type']);
        $roles = Db::name('role')->where($con)->order("id DESC")->select();
        //督导列表
        $where=array();
        $userList=get_user_list($adminid);
        $uid_list_str=toStr($userList,'userid');
        if($uid_list_str == '')
        {
            $uid_list_str=$adminid;
            $where['steer']=$uid_list_str;
        }else{
            $uid_list_str=$uid_list_str.','.$adminid;
            $where['steer']=array('in',$uid_list_str);
        }
        $st=array('1','-1');
        $where['status']=array('in',$st);
        //var_dump($where);die();
        $store_list=Db::name('store')->where($where)->select()->toarray();
        $map=array();
        $list = Db::name('store')->where($map)->field('id,store_name')->order('id desc')->select();
        $this->assign("roles", $roles);
        $this->assign('role_type',$uinfo['role_type']);
        $this->assign('list',$list);
        //$this->assign('dudao_list',$dudao_list);
        $this->assign('store_list',$store_list);
        return $this->fetch();
    }

    /**
     * 管理员添加提交
     * @adminMenu(
     *     'name'   => '管理员添加提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {                 
                $uid=cmf_get_current_admin_id();
                $uinfo=get_operator_data($uid);
                $role_ids = $_POST['role_id'];
                unset($_POST['dudaoid']);
                unset($_POST['role_id']);
                $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                $_POST['store_id'] = isset($_POST['store_id'])?$_POST['store_id']:'';
                $_POST['role_type']=$role_ids[0];
                if(empty($_POST['mobile'])){
                   $this->error('手机号不能为空'); 
                }
                $check_mobile=Db::name('User')->where(array('mobile'=>$_POST['mobile']))->find();
                if($check_mobile){
                    $this->error('该手机号已经存在！');exit;
                }
                if(empty($_POST['user_login'])){
                    $this->error('用户名不能为空');
                }
                $user_login=Db::name('User')->where(array('user_login'=>$_POST['user_login']))->find();
                if($user_login){
                    $this->error('该用户名已存在！');exit;
                }
                //设置userid  2018/06/01 name 乾坤
                $rand = rand(1000,9999);
                $_POST['id']= date("His",time()).$rand;
                $result = DB::name('user')->insert($_POST);
                if($result > 0){
                    $result = $_POST['id'];
                    if ($result !== false) {
                        foreach ($role_ids as $role_id) {
                            if ($uid != 1 && $role_id == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            Db::name('RoleUser')->insert(["role_id" => $role_id, "user_id" => $result]);
                        }
                        //添加关系网
                        adduser($result,$uid,$_POST['role_type']);
                        //如果添加的是店长则存一下user表
                        if($_POST['store_id']&&$role_ids[0] == 13){
                            $res=Db::name('Store')->where('id='.$_POST['store_id'])->update(['ownerid'=>$result]);
                        }
                        $this->success("添加成功！", url("user/index"));
                    }else{
                        $this->error("添加失败！");
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }
        }
    }

    /**
     * 管理员编辑
     * @adminMenu(
     *     'name'   => '管理员编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员编辑',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $adminid = cmf_get_current_admin_id();
        $uinfo=get_operator_data($adminid);
        $id    = $this->request->param('id', 0, 'intval');
        $con['status']=1;       
        $con['id']=array('gt',$uinfo['role_type']);
        $roles = DB::name('role')->where($con)->order("id DESC")->select();        
                
        //督导列表
//         $where=array();
//         if($uinfo['role_type'] == 4){
//             $where['refereeid']=$adminid;
//             $where['distance']=1;
//         }  
        $userList=get_user_list($adminid);
        $uid_list_str=toStr($userList,'userid');
        $uid_list_str=$uid_list_str.','.$adminid;
       //dump($uid_list_str);
        $where['steer']=array('in',$uid_list_str);
        $st=array('1','-1');
        $where['status']=array('in',$st);
        $store_list=Db::name('Store')->where($where)->select()->toarray();
       // echo Db::name('Store')->getlastsql();
        $role_ids = DB::name('RoleUser')->where(["user_id" => $id])->column("role_id");        $this->assign("roles", $roles);
        $this->assign("role_ids", $role_ids);
        $user = DB::name('user')->where(["id" => $id])->find();
        $this->assign($user);        $this->assign('uinfo',$user);
        $this->assign('role_type',$uinfo['role_type']);
        $this->assign('store_list',$store_list);
        //$this->assign('list',$list);
        //$this->assign('dudao_list',$dudao_list);
        return $this->fetch();
    }

    /**
     * 管理员编辑提交
     * @adminMenu(
     *     'name'   => '管理员编辑提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员编辑提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                if (empty($_POST['user_pass'])) {
                    unset($_POST['user_pass']);
                } else {
                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                }
                $role_ids = $this->request->param('role_id/a');
                unset($_POST['role_id']);
//                 $dudaoid='';
//                 if(isset($_POST['dudaoid'])){
//                     $dudaoid=$_POST['dudaoid'];
//                     unset($_POST['dudaoid']);
//                 }
                $_POST['role_type']=$role_ids[0];
                $result = DB::name('user')->update($_POST);
                if ($result !== false) {
                    $uid = $this->request->param('id', 0, 'intval');
                    DB::name("RoleUser")->where(["user_id" => $uid])->delete();
                    
                    foreach ($role_ids as $role_id) {
                        if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                            $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                        }
                        DB::name("RoleUser")->insert(["role_id" => $role_id, "user_id" => $uid]);
                    }
                    //关系排网
                    DB::name("UserReferee")->where(["userid" => $uid])->delete();//清除原来的排网
                    adduser($_POST['id'],cmf_get_current_admin_id(),$_POST['role_type']);                    
                    if($_POST['store_id']&&$role_ids[0] == 13){
                        $res=Db::name('Store')->where('id='.$_POST['store_id'])->update(['ownerid'=>$_POST['id']]);
                    }
                    $this->success("保存成功！",url("User/index"));
                } else {
                    $this->error("保存失败！",url("User/index"));
                }
            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }

    /**
     * 管理员个人信息修改
     * @adminMenu(
     *     'name'   => '个人信息',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员个人信息修改',
     *     'param'  => ''
     * )
     */
    public function userInfo()
    {
        $id   = cmf_get_current_admin_id();
        $user = Db::name('user')->where(["id" => $id])->find();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 管理员个人信息修改提交
     * @adminMenu(
     *     'name'   => '管理员个人信息修改提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员个人信息修改提交',
     *     'param'  => ''
     * )
     */
    public function userInfoPost()
    {
        if ($this->request->isPost()) {

            $data             = $this->request->post();
            $data['birthday'] = strtotime($data['birthday']);
            $data['id']       = cmf_get_current_admin_id();
            $create_result    = Db::name('user')->update($data);;
            if ($create_result !== false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    /**
     * 管理员删除
     * @adminMenu(
     *     'name'   => '管理员删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 1) {
            $this->error("最高管理员不能删除！");
        }
        if (Db::name('user')->delete($id) !== false) {
            Db::name("RoleUser")->where(["user_id" => $id])->delete();
            Db::name("UserReferee")->where(["userid" => $id])->delete();
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }
    /**
     * 停用管理员
     * @adminMenu(
     *     'name'   => '停用管理员',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '停用管理员',
     *     'param'  => ''
     * )
     */
    public function ban()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!empty($id)) {
            $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '0');
            if ($result !== false) {
                $this->success("管理员停用成功！", url("user/index"));
            } else {
                $this->error('管理员停用失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 启用管理员
     * @adminMenu(
     *     'name'   => '启用管理员',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '启用管理员',
     *     'param'  => ''
     * )
     */
    public function cancelBan()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!empty($id)) {
            $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '1');
            if ($result !== false) {
                $this->success("管理员启用成功！", url("user/index"));
            } else {
                $this->error('管理员启用失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }
    /**
     * 更换上级管理员
     * 
     */
    public function change(){
        $id    = $this->request->param('id', 0, 'intval');
        $adminid = cmf_get_current_admin_id();
        $uinfo=Db::name('User')->where(array('id'=>$id))->find();
        $userList=get_user_list($adminid);
        $uid_list_str=toStr($userList,'userid');
        $uid_list_str.=','.$adminid;
        $uid_list_str=str_replace($id,'',$uid_list_str);
        $list=Db::name('User')->where(array('id'=>array('in',$uid_list_str)))->select()->toarray();
        $tuijian=Db::name('UserReferee')->where(array('userid'=>$id,'distance'=>1,'status'=>1))->find();       
        //$this->assign('role_type',$uinfo['role_type']);
        $this->assign('list',$list);
        $this->assign('tuijian',$tuijian);
        $this->assign('id',$id);
        return $this->fetch();
    }
    /**
     * 更换上级管理员
     */
    public function changePost(){
        if ($this->request->isPost()){           
            //关系排网
            DB::name("UserReferee")->where(["userid" => $_POST['id']])->update(['status' =>0]);//关闭原来的排网
            //判断一下该是不是店长
            $check= DB::name("Store")->where(array('ownerid'=>$_POST['id']))->find();
            $re=adduser($_POST['id'],$_POST['upid']);
            if($check){
                DB::name("Store")->where(["id" => $check['id']])->update(['steer' =>$_POST['upid']]);
            }
            if($re){
                $this->success('修改成功！');
            }else{
                $this->error('修改失败！');
            }
        }
    }
}